<?php

Class Router {
	private $request;
	private $path;
	private $file;
	
	
	function __construct() {
		$this->request = new Request();

	}
	
	
	//comprovar l'exitencia del fitxer 	
	//comprovar els permisos de lectura
	//comprovar que es una ruta valida de l'aplicació, no pot agafar qualsevol ruta del servidor amb ../../
	//comprovar que exitex l'acció demanada al controlador
	//agafar el controldor  i acció per defecte
	//inspecció del request??
	
	
	private function getRouteParams($route){
		//Si no exitex la ruta ??
		if(empty($route)){
			$controller="index";
			$action ="index";
		}		
		else{		
			// Tractem la entrada de la ruta
			$route = trim($route, '/\\');
			$parts =  explode('/', $route);
			
			//La ruta te totes les parts? agafem la per defecte o excepció?
			$controller=$parts[0];
			(empty($parts[1])) ? $action ="index" : $action=$parts[1];
		}
		$ca= array('controller'=>$controller,'action'=>$action);
		return $ca;
		
		
	}
	
	
	private function chkController($controller){
		$tmpfile=$this->path. DIRSEP .$controller.'.php';
		// existeix el controlador ?
		if (file_exists($tmpfile) == false) {
			throw new RouterException(RouterException::ERR_FILE_NOT_EXISTS,"<b>".$tmpfile."</b>");
		}
		// Es pot llegir el controlador?
		if (is_readable($tmpfile) == false) {
			throw new RouterException(RouterException::ERR_CANNOT_READ_FILE,"<b>".$tmpfile."</b>");
		}
		$this->file=$tmpfile;
	}
	
	
	private function chkAction($controller,$action){
			
		// L'acció està disponible?
		if (is_callable(array($controller, $action)) == false) {
			throw new RouterException(RouterException::ERR_ACTION_NOT_AVAILABLE,"<b>".get_class($controller).'=>'.$action."</b>");
			
		}

	
	}
	
	public function callController(){
		$route=$this->getRouteParams($this->request->getParam('route'));
		$this->chkController($route['controller']);
		
		// Include the file
		include ($this->file);		
		
		//Instanciem la classe per provar-la
		$class = 'Controller_' .ucfirst($route['controller']);
		$controller = new $class();
		
		$this->chkAction($controller,$route['action']);

		
		// Run action
		$controller->$route['action']();	
	
	} 
	
	
	public static function redirection($controller='index',$action='index'){
		//analitzem el path
		$controller=strtolower ($controller);
		$path=site_path . 'controllers';
		$path = rtrim($path, '/\\');
		$path .= DIRSEP;
		
		if (is_dir($path) == false) {
			throw new RouterException(RouterException::ERR_INV_CONT_PATH,"<b>".$path."</b>");
		}

		//comprovem l'exitencia del fitxer
		$file=$path. DIRSEP .$controller.'.php';

		// existeix el controlador ?
		if (file_exists($file) == false) {
			throw new RouterException(RouterException::ERR_FILE_NOT_EXISTS,"<b>".$file."</b>");
		}
		// Es pot llegir el controlador?
		if (is_readable($file) == false) {
			throw new RouterException(RouterException::ERR_CANNOT_READ_FILE,"<b>".$file."</b>");
		}
		
		
		// Include the file
		include ($file);		
		
		//Instanciem la classe per provar-la
		$class = 'Controller_' .ucfirst($controller);
		$obj = new $class();
		
		if (is_callable(array($obj, $action)) == false) {
			throw new RouterException(RouterException::ERR_ACTION_NOT_AVAILABLE,"<b>".get_class($obj).'=>'.$action."</b>");
			
		}
			
		//action
		$obj->$action();	
	}
	


	public function setPath($path) {
		
		$path = rtrim($path, '/\\');
		$path .= DIRSEP;
		if (is_dir($path) == false) {
			throw new RouterException(RouterException::ERR_INV_CONT_PATH,"<b>".$path."</b>");
		}

		$this->path = $path;
	}
	
	
	/*
	// Antiga estructura !!!

	function getArg($key) {
		if (!isset($this->args[$key])) { return null; }
		return $this->args[$key];
	}

	function delegate() {
		
		// Analyze route
		$this->getController($file, $controller, $action, $args);
		
		// File exists ?
		if (file_exists($file) == false) {
			throw new RouterException(RouterException::ERR_FILE_NOT_EXISTS,"<b>".$file."</b>");
			
		}
		
		// File available?
		if (is_readable($file) == false) {
			throw new RouterException(RouterException::ERR_CANNOT_READ_FILE,"<b>".$file."</b>");
			
		}

		// facilita el nom del request
		$request=$this->registry['request'];		
		
		// Include the file
		include ($file);

		// Initiate the class
		$class = 'Controller_' . $controller;
		$controller = new $class($this->registry);

		// Action available?
		if (is_callable(array($controller, $action)) == false) {
			throw new RouterException(RouterException::ERR_ACTION_NOT_AVAILABLE,"<b>".$class.'=>'.$action."</b>");
			
		}

		// Run action
		$controller->$action();
	}

	private function extractArgs($args) {
		if (count($args) == 0) { return false; }
		$this->args = $args;
	}
	
	private function getController(&$file, &$controller, &$action, &$args) {
		$route = (empty($_GET['route'])) ? '' : $_GET['route'];

		if (empty($route)) { $route = 'index'; }

		// Get separate parts
		$route = trim($route, '/\\');
		$parts = explode('/', $route);

		// Find right controller
		$cmd_path = $this->path;
		foreach ($parts as $part) {
			$fullpath = $cmd_path . $part;
			
			// Is there a dir with this path?
			if (is_dir($fullpath)) {
				$cmd_path .= $part . DIRSEP;
				array_shift($parts);
				continue;
			}

			// Find the file
			if (is_file($fullpath . '.php')) {
				$controller = $part;
				array_shift($parts);
				break;
			}
		}

		if (empty($controller)) { $controller = 'index'; };

		// Get action
		$action = array_shift($parts);
		if (empty($action)) { $action = 'index'; }

		$file = $cmd_path . $controller . '.php';
		$args = $parts;
	}

	*/


}

?>